package com.gqr.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:AtomicLongDemo
 * author:guqingrong
 * Date:2024-05-14 21:54
 * Description:演示高并发场景下LongAdder比AtomicLong性能好
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class LongAdderDemo {
    public static void main(String[] args) throws InterruptedException {
        LongAdder counter = new LongAdder();

        ExecutorService service = Executors.newFixedThreadPool(20);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            service.submit( new Task(counter));
        }
        service.shutdown();
        while (!service.isTerminated()){

        }

        long end = System.currentTimeMillis();
        System.out.println("LongAdder耗时"+ (end-start));
        System.out.println(counter.sum());
    }

    private static class Task implements Runnable{

        private LongAdder counter;

        public Task(LongAdder counter) {
            this.counter = counter;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                counter.increment();
            }
        }
    }
}
